package com.lizx.persional.service.impl;

import com.baomidou.kisso.SSOAuthorization;
import com.baomidou.kisso.security.token.SSOToken;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lizx.persional.entity.vo.MenuSelectVo;
import com.lizx.persional.entity.Resources;
import com.lizx.persional.dao.ResourcesDao;
import com.lizx.persional.service.ResourcesService;
import com.lizx.persional.common.base.SuperServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.security.Permission;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 李振兴
 * @since 2018-02-27
 */
@Service
public class ResourcesServiceImpl extends SuperServiceImpl<ResourcesDao, Resources> implements ResourcesService , SSOAuthorization{

    /**
     * 根据用户id查询菜单列表
     *
     * @param userId
     * @return
    */
    @Override
    public List<MenuSelectVo> selectMenuByUserId(Long userId) {
        EntityWrapper<Resources> ew = new EntityWrapper<>();
        ew.eq("type",0)
                .eq("is_enable",true)
                .eq("is_deleted",false);

        List<MenuSelectVo> menuSelectVoList = baseMapper.selectMenuByUserId(userId,ew);
        if (menuSelectVoList == null) {
            return null;
        }

        List<MenuSelectVo> mvList = new ArrayList<>();
        for (MenuSelectVo menuSelectVo : menuSelectVoList){
            ew = new EntityWrapper<>();
            ew.eq("type",1)
                    .eq("is_enable",true)
                    .eq("is_deleted",false)
                    .eq("pid",menuSelectVo.getId());
            menuSelectVo.setMenuSelectVoList(baseMapper.selectMenuByUserId(userId,ew));
            mvList.add(menuSelectVo);
        }
        return mvList;
    }

    /**
     * 轮询用户权限是否匹配
     * @param token
     * @param code
     * @return
     */
    @Override
    public boolean isPermitted(SSOToken token, String code) {
        if (StringUtils.isNotBlank(code)) {
            List<Resources> resourcesList = baseMapper.selectAllResourceByUserId(Long.valueOf(token.getId()));
            if (resourcesList != null) {
                for (Resources resources : resourcesList) {
                    if (code.equals(resources.getCode())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
